from flask import current_app
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info.models import User
from info.utils.commons import user_login_data
from . import admin_blue


# 后台主页内容
# 请求路径: /admin/index
# 请求方式: GET
# 请求参数: 无
# 返回值:渲染页面index.html,user字典数据
@admin_blue.route('/index')
@user_login_data
def admin_index():
    # 判断用户是否是管理员
    if not session.get("is_admin"):
        return redirect('/')

    return render_template('admin/index.html', user=g.user.to_dict())


# 获取/登陆,管理员登陆
# 请求路径: /admin/login
# 请求方式: GET,POST
# 请求参数:GET,无, POST,username,password
# 返回值: GET渲染login.html页面, POST,login.html页面,errmsg
@admin_blue.route('/login', methods=["GET", "POST"])
def admin_login():
    # return render_template("admin/login.html")
    if request.method == "GET":
        # 判断用户是否有登陆过
        if session.get("is_admin"):
            return redirect('/admin/index')
        return render_template("admin/login.html")

    # 2,如果post
    # 2.1 获取参数
    username = request.form.get("username")
    password = request.form.get("password")

    # 2.2 校验参数
    # 为空校验
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不全")

    # 密码校验
    try:
        admin = User.query.filter(User.nick_name == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="该用户失败")

    if not admin:
        return render_template("admin/login.html", errmsg="该用户不存在")

    if not admin.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码出错了")

    # 2.3 状态保持
    session["user_id"] = admin.id
    session["nick_name"] = username
    session["is_admin"] = True

    # 2.4 返回响应
    # return redirect("http://www.taobao.com")
    return redirect("/admin/index")
